package com.guli.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.guli.common.to.MemberPriceTo;
import com.guli.common.to.SkuFullReductionTo;
import com.guli.common.to.SkuLadderTo;
import com.guli.common.to.SpuBoundsTo;
import com.guli.common.utils.Query;
import com.guli.common.utils.R;
import com.guli.gulimall.product.config.GuliESConfig;
import com.guli.gulimall.product.dao.*;
import com.guli.gulimall.product.entity.*;
import com.guli.gulimall.product.feign.CouponFeign;
import com.guli.gulimall.product.service.*;
import com.guli.gulimall.product.vo.*;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;

import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @SuppressWarnings("all")
    @Autowired
    RestHighLevelClient client;
    @SuppressWarnings("all")
    @Autowired
    SpuInfoDescDao spuInfoDescDao;

    @Autowired
    SpuImagesService spuImagesService;


    @SuppressWarnings("all")
    @Autowired
    SkuSaleAttrValueDao skuSaleAttrValueDao;
    @SuppressWarnings("all")
    @Autowired
    AttrDao attrDao;

    @SuppressWarnings("all")
    @Autowired
    ProductAttrValueService productAttrValueService;


    @SuppressWarnings("all")
    @Autowired
    ProductAttrValueDao productAttrValueDao;

    @SuppressWarnings("all")
    @Autowired
    SkuInfoDao skuInfoDao;

    @SuppressWarnings("all")
    @Autowired
    BrandDao brandDao;

    @SuppressWarnings("all")
    @Autowired
    CategoryDao categoryDao;
    @SuppressWarnings("all")
    @Autowired
    SkuImagesService skuImagesService;

    @SuppressWarnings("all")
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @SuppressWarnings("all")
    @Autowired
    CouponFeign couponFeign;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void addSpuVo(SpuVo spuVo) {
//        商品发布表结构
//
//                ----pms 和 sms 数据库 ---
//
//
//                pms数据库
//

//        spu基本信息
//
//        1:spu基本信息 pms_spu_info
        //拿到添加表的数据
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        //直接复制给spuinfo
        BeanUtils.copyProperties(spuVo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        baseMapper.insert(spuInfoEntity);
//        2:spu的描述信息 pms_spu_info_desc
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        List<String> decript = spuVo.getDecript();
        if (!decript.isEmpty()){
            String url = "";
            //字符串拼接图片路径
            for (String s : decript) {
                url += ";"+s;
            }
            url = url.substring(1);
            spuInfoDescEntity.setDecript(url);
        }
        spuInfoDescDao.insert(spuInfoDescEntity);
//        3:spu的所有图集 pms_spu_images

        List<String> images = spuVo.getImages();
        if (!images.isEmpty()){
            List<SpuImagesEntity> collect = images.stream().map(imgurl -> {
                SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                spuImagesEntity.setSpuId(spuInfoEntity.getId());
                spuImagesEntity.setImgUrl(imgurl);
                return spuImagesEntity;
            }).collect(Collectors.toList());
            //批量添加 因为没有dao层没有批量添加 需要用到service
            spuImagesService.saveBatch(collect);
        }
//        4:spu页面选中规格和销售参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuVo.getBaseAttrs();
        if (!baseAttrs.isEmpty()){
            List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
                ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
                productAttrValueEntity.setSpuId(spuInfoEntity.getId());
                productAttrValueEntity.setAttrId(attr.getAttrId());
                productAttrValueEntity.setAttrValue(attr.getAttrValues());
//                productAttrValueEntity.set
                AttrEntity attrEntity = attrDao.selectById(attr.getAttrId());
                productAttrValueEntity.setAttrName(attrEntity.getAttrName());
                productAttrValueEntity.setQuickShow(attrEntity.getShowDesc());
                return productAttrValueEntity;
            }).collect(Collectors.toList());
            productAttrValueService.saveBatch(collect);
        }
//        5:使用openfegin调用优惠券服务保存成长值和积分 sms_spu_bounds

        Bounds bounds = spuVo.getBounds();
        if (bounds!=null){
            SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
            spuBoundsTo.setSpuId(spuInfoEntity.getId());
            spuBoundsTo.setBuyBounds(bounds.getBuyBounds());
            spuBoundsTo.setGrowBounds(bounds.getGrowBounds());
            R r = couponFeign.saveSpuBoundsTo(spuBoundsTo);
        }

//
//        spu基本信息保存结束
//
//                sku基本信息
//
//

        List<Skus> skus = spuVo.getSkus();
        if (!skus.isEmpty()){
            for (Skus sku : skus) {

//        6:sku基本信息 pms_sku_info
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku,skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0l);
                skuInfoEntity.setSkuDesc(spuInfoEntity.getSpuDescription());
                skuInfoEntity.setSpuId(spuInfoEntity.getId());

                List<Images> images1 = sku.getImages();
                if (!images1.isEmpty()){
                    Images images2 = images1.stream().filter(fliteurl -> {
                        return fliteurl.getDefaultImg().equals(1);
                    }).findFirst().get();
                    skuInfoEntity.setSkuDefaultImg(images2.getImgUrl());
                }
                skuInfoDao.insert(skuInfoEntity);
//        7:每个sku的图片信息 pms_sku_images
                if (!images1.isEmpty()){
                    List<SkuImagesEntity> collect = images1.stream().filter(filter -> {
                        return filter.getImgUrl() != null && filter.getImgUrl().length() > 0;
                    }).map(filter -> {
                        SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                        skuImagesEntity.setImgUrl(filter.getImgUrl());
                        skuImagesEntity.setDefaultImg(filter.getDefaultImg());
                        skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                        return skuImagesEntity;
                    }).collect(Collectors.toList());
                    skuImagesService.saveBatch(collect);
                }
//        8:每个sku的销售属性 pms_sku_sale_attr_value
                List<Attr> attr = sku.getAttr();
                if (!attr.isEmpty()){
                    List<SkuSaleAttrValueEntity> collect = attr.stream().map(item -> {
                        SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                        BeanUtils.copyProperties(item,skuSaleAttrValueEntity);
                        skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                        return skuSaleAttrValueEntity;
                    }).collect(Collectors.toList());
                    skuSaleAttrValueService.saveBatch(collect);
                }
//        sku保存结束
//
//
//                sms数据库
//
//        9:打折表 sms_sku_ladder
                SkuLadderTo skuLadderTo = new SkuLadderTo();
                skuLadderTo.setSkuId(skuInfoEntity.getSkuId());
                skuLadderTo.setFullCount(sku.getFullCount());
                skuLadderTo.setDiscount(sku.getDiscount());
                skuLadderTo.setAddOther(sku.getCountStatus());
                R r = couponFeign.saveSkuLadderTo(skuLadderTo);

//        10:满减表 sms_sku_full_reduction

                SkuFullReductionTo skuFullReductionTo = new SkuFullReductionTo();
                skuFullReductionTo.setFullPrice(sku.getFullPrice());
                skuFullReductionTo.setReducePrice(sku.getReducePrice());
                skuFullReductionTo.setSkuId(skuInfoEntity.getSkuId());
                skuFullReductionTo.setAddOther(sku.getCountStatus());
                R r1 = couponFeign.saveSkuFullReductionEntity(skuFullReductionTo);

//        11:会员价格表 sms_member_price
                List<MemberPrice> memberPrice = sku.getMemberPrice();
                if (!memberPrice.isEmpty()){
                    List<MemberPriceTo> collect = memberPrice.stream().map(item -> {
                        MemberPriceTo memberPriceTo = new MemberPriceTo();
                        memberPriceTo.setMemberLevelId(item.getId());
                        memberPriceTo.setMemberLevelName(item.getName());
                        memberPriceTo.setSkuId(skuInfoEntity.getSkuId());
                        memberPriceTo.setMemberPrice(item.getPrice());
                        return memberPriceTo;
                    }).collect(Collectors.toList());
                    couponFeign.saveMemberPriceTo(collect);
                }
            }//结束循环
        }//判断条件
//
    }

    @Override
    public void up(Long spuId) {
        try {
            //先查到当前的spuinfo
            //先通过spuId查询到spu的信息
            SpuInfoEntity spuInfoEntity = baseMapper.selectById(spuId);
            spuInfoEntity.setPublishStatus(1);
            baseMapper.updateById(spuInfoEntity);
            List<SpuEsVo.AttrEsVo> attrlist = new ArrayList<>();
            //通过spuId查询到所有的sku信息
            List<SkuInfoEntity> skus = skuInfoDao.selectList(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
            //查询spu里面需要检索的规格参数
            List<ProductAttrValueEntity> productlist = productAttrValueDao.getByattrvalue(spuId);

            if (!productlist.isEmpty()){
                attrlist = productlist.stream().map(item -> {
                    SpuEsVo.AttrEsVo attrEsVo = new SpuEsVo.AttrEsVo();
                    attrEsVo.setAttrId(item.getAttrId());
                    attrEsVo.setAttrName(item.getAttrName());
                    attrEsVo.setAttrValue(item.getAttrValue());
                    return attrEsVo;
                }).collect(Collectors.toList());
            }


            //最终实现的是把需要检索的规格参数 和所有的销售属性 和sku里面所有的属性赋值给新的vo 下面for循环就实现了所有的封装
            //遍历sku
            BulkRequest blukrequest = new BulkRequest();
            for (SkuInfoEntity sku : skus) {
                IndexRequest request = new IndexRequest("product");
                SpuEsVo spuEsVo = new SpuEsVo();
                BeanUtils.copyProperties(sku,spuEsVo);
                //品牌
                BrandEntity brandEntity = brandDao.selectById(spuInfoEntity.getBrandId());
                spuEsVo.setBrandId(spuInfoEntity.getBrandId());
                spuEsVo.setBrandName(brandEntity.getName());
                spuEsVo.setBrandImg(brandEntity.getLogo());
                //分类
                CategoryEntity categoryEntity = categoryDao.selectById(spuInfoEntity.getCatalogId());
                spuEsVo.setCatalogName(categoryEntity.getName());
                spuEsVo.setCatalogId(spuInfoEntity.getCatalogId());

                spuEsVo.setHasStock(true);
                spuEsVo.setHotScore(0d);
                spuEsVo.setSaleCount(0l);
                spuEsVo.setSkuImg(sku.getSkuDefaultImg());
                spuEsVo.setSkuPrice(sku.getPrice());

                //收集到sku里面所有的销售属性

                List<SkuSaleAttrValueEntity> saleattrs = skuSaleAttrValueDao.selectList(new QueryWrapper<SkuSaleAttrValueEntity>().eq("sku_id", sku.getSkuId()));

                List<SpuEsVo.AttrEsVo> collect = saleattrs.stream().map(item -> {
                    SpuEsVo.AttrEsVo attrEsVo = new SpuEsVo.AttrEsVo();
                    attrEsVo.setAttrId(item.getAttrId());
                    attrEsVo.setAttrName(item.getAttrName());
                    attrEsVo.setAttrValue(item.getAttrValue());
                    return attrEsVo;
                }).collect(Collectors.toList());
                collect.addAll(attrlist);
                spuEsVo.setAttrs(collect);
                //es封装结束
                request.id(sku.getSkuId().toString());
                String json = JSON.toJSONString(spuEsVo);
                request.source(json, XContentType.JSON);

                blukrequest.add(request);

            }
            BulkResponse bulkResponse = client.bulk(blukrequest, GuliESConfig.COMMON_OPTIONS);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}